// 路由鉴权
import router from "@/router";
import nprogress from 'nprogress'
import "nprogress/nprogress.css"
import setting from './setting'
nprogress.configure({ showSpinner: false })

// 引入大仓库
import pinia from './store'
// 获取用户相关的小仓库内部token数据，判断是否登录
import useUserStore from './store/modules/user'
let userStore = useUserStore(pinia)

// 全局守卫：项目当中任意路由切换都会触发的钩子
// 全局前置守卫
router.beforeEach(async (to: any, from: any, next: any) => {
  document.title = `${setting.title} - ${to.meta.title}`
  nprogress.start()
  let token = userStore.token
  let username = userStore.username

  if (token) {
    // 登录成功，访问login，不能访问，指向首页
    if (to.path == '/login') {
      next({ path: '/' })
    } else {
      // next()
      if (username) {
        next()
      } else {
        try {
          await userStore.userInfo()
          next()
        } catch (error) {
          await userStore.userLogout()
          next({ path: '/login', query: { redirect: to.path } })
        }
      }
    }
  } else {
    if (to.path == '/login') {
      next()
    } else {
      next({ path: '/login', query: { redirect: to.path } })
    }
  }
})
// 全局后置守卫
router.afterEach((to: any, from: any) => {
  nprogress.done()
})